package cumeo89.chii.client.wikt;

import static cumeo89.chii.client.util.StringUtil.*;
import cumeo89.chii.client.util.JSStringArray;
import cumeo89.chii.client.util.ReplaceDelegate;

class WikitextRenderer {

	private WikitextRenderer() {
	}

	public static String toHtml(Wiktionary wikt, String wikitext) {
		if (wikitext == null) {
			return "";
		}
		return renderMarkupSyntax(wikt, replaceCommonTemplates(wikitext));
	}

	private static String replaceCommonTemplates(String wikitext) {
		// support {{see-entry}} and {{like-entry}}
		wikitext = wikitext.replaceAll("\\{\\{like-entry\\|([^}]+)\\}\\}",
				"''Như '''[[$1]]'''.''");
		wikitext = wikitext.replaceAll("\\{\\{see-entry\\|([^}]+)\\}\\}",
				"''Xem '''[[$1]]'''.''");

		return wikitext;
	}

	private static String renderMarkupSyntax(final Wiktionary wikt,
			String wikitext) {
		// replace '', ''' with <b>, <i>
		// code na`y kho^ng quet he^t cac truong ho*.p, chi? ta.m du? du`ng :-|
		int italic = -1, bold = -1;
		JSStringArray a = split(wikitext, "('{2,})");
		for (int i = 1; i < a.length(); i += 2) {
			int l = a.get(i).length();
			if (l >= 3) {
				if (bold > 0) {
					if (bold >= italic) {
						a.set(bold, "<b>" + a.get(bold).replace("'''", ""));
						a.set(i, a.get(i).replaceFirst("'''", "") + "</b>");
						bold = -1;
						l -= 3;
					}
				} else {
					bold = i;
					l -= 3;
				}
			}
			if (l >= 2) {
				if (italic > 0) {
					if (italic >= bold) {
						a.set(italic, "<i>" + a.get(italic).replace("''", ""));
						a.set(i, a.get(i).replaceFirst("''", "") + "</i>");
						italic = -1;
						l -= 2;
					}
				} else {
					italic = i;
					l -= 2;
				}
			}
		}
		wikitext = a.join("");

		// render link
		wikitext = replaceAll(wikitext,
				"\\[\\[(?:([^\\[\\]|]+)\\|)?([^\\[\\]|]+)\\]\\]",
				new ReplaceDelegate() {

					public String getReplacementOf(JSStringArray a) {
						return "<span href='" + wikt.getBase()
								+ "index.php?title="
								+ (isEmpty(a.get(1)) ? a.get(2) : a.get(1))
								+ "' class='wikitext-link'>" + a.get(2)
								+ "</span>";
					}
				});

		return wikitext;
	}

}
